"""
改进建议生成服务实现

提供针对性的研究质量改进建议，包括：
- 基于问题的改进建议生成
- 建议优先级排序
- 建议效果预测
- 个性化建议定制
"""
import math
from typing import List, Dict, Any, Optional, Tuple
from datetime import datetime, timedelta
from dataclasses import asdict

from ..models.analysis_models import (
    QualityIssue, Improvement, QualityAssessment, EffectReport
)


class ImprovementSuggestionService:
    """改进建议生成服务"""
    
    def __init__(self):
        # 改进建议模板库
        self.suggestion_templates = {
            'methodology': {
                'sample_size': {
                    'template': '增加样本量到至少{target_size}个，当前样本量({current_size})可能导致统计检验功效不足',
                    'priority': 'high',
                    'effort': 'high',
                    'timeline': '2-4周',
                    'expected_impact': 0.3,
                    'resources': ['时间', '人力', '资金'],
                    'steps': [
                        '重新计算所需样本量',
                        '制定数据收集计划',
                        '扩大招募范围',
                        '验证新数据质量'
                    ]
                },
                'randomization': {
                    'template': '实施随机化分配方案，可使用{methods}等方法确保实验对象的随机分配',
                    'priority': 'high',
                    'effort': 'medium',
                    'timeline': '1-2周',
                    'expected_impact': 0.25,
                    'resources': ['统计软件', '随机化工具'],
                    'steps': [
                        '选择合适的随机化方法',
                        '生成随机分配序列',
                        '实施分配方案',
                        '记录分配过程'
                    ]
                },
                'control_variables': {
                    'template': '增加{suggested_vars}等控制变量，以减少混杂因素的影响',
                    'priority': 'medium',
                    'effort': 'medium',
                    'timeline': '1-3周',
                    'expected_impact': 0.2,
                    'resources': ['测量工具', '数据收集'],
                    'steps': [
                        '识别潜在混杂变量',
                        '设计测量方案',
                        '收集控制变量数据',
                        '在分析中纳入控制变量'
                    ]
                }
            },
            'data_quality': {
                'completeness': {
                    'template': '改进数据收集方法，将数据完整性从{current_rate:.1%}提升到至少85%',
                    'priority': 'high',
                    'effort': 'medium',
                    'timeline': '2-3周',
                    'expected_impact': 0.25,
                    'resources': ['数据收集工具', '质量控制'],
                    'steps': [
                        '分析数据缺失模式',
                        '改进数据收集流程',
                        '实施质量控制措施',
                        '验证数据完整性'
                    ]
                },
                'reliability': {
                    'template': '使用权威数据源如{suggested_sources}，确保数据来源的可靠性',
                    'priority': 'high',
                    'effort': 'medium',
                    'timeline': '1-2周',
                    'expected_impact': 0.3,
                    'resources': ['数据库访问', '数据许可'],
                    'steps': [
                        '评估现有数据源',
                        '寻找权威替代源',
                        '获取数据访问权限',
                        '验证数据质量'
                    ]
                }
            },
            'analysis': {
                'method_selection': {
                    'template': '采用{suggested_methods}等更适合的分析方法，以提高分析的有效性',
                    'priority': 'high',
                    'effort': 'medium',
                    'timeline': '1-2周',
                    'expected_impact': 0.25,
                    'resources': ['统计软件', '方法学习'],
                    'steps': [
                        '评估数据特征',
                        '选择合适的分析方法',
                        '学习方法实施',
                        '验证分析结果'
                    ]
                },
                'statistical_testing': {
                    'template': '添加{test_types}等统计显著性检验，确保结果的统计可靠性',
                    'priority': 'medium',
                    'effort': 'low',
                    'timeline': '3-5天',
                    'expected_impact': 0.15,
                    'resources': ['统计软件'],
                    'steps': [
                        '选择合适的统计检验',
                        '设定显著性水平',
                        '执行统计检验',
                        '解释检验结果'
                    ]
                }
            },
            'reproducibility': {
                'code_sharing': {
                    'template': '在{platforms}等平台公开完整的实现代码，提高研究的可重现性',
                    'priority': 'high',
                    'effort': 'medium',
                    'timeline': '1-2周',
                    'expected_impact': 0.3,
                    'resources': ['代码整理', '平台账号'],
                    'steps': [
                        '整理和清理代码',
                        '添加详细注释',
                        '创建使用说明',
                        '发布到公开平台'
                    ]
                },
                'data_sharing': {
                    'template': '在符合{privacy_requirements}的前提下，公开研究数据和数据字典',
                    'priority': 'high',
                    'effort': 'medium',
                    'timeline': '1-3周',
                    'expected_impact': 0.25,
                    'resources': ['数据处理', '隐私审查'],
                    'steps': [
                        '评估数据隐私要求',
                        '处理敏感信息',
                        '创建数据字典',
                        '发布数据集'
                    ]
                },
                'documentation': {
                    'template': '完善研究文档，包括{doc_types}等，提高文档完整性到85%以上',
                    'priority': 'medium',
                    'effort': 'medium',
                    'timeline': '1-2周',
                    'expected_impact': 0.2,
                    'resources': ['文档编写时间'],
                    'steps': [
                        '评估现有文档',
                        '识别缺失内容',
                        '编写补充文档',
                        '审查文档质量'
                    ]
                }
            },
            'novelty': {
                'literature_review': {
                    'template': '扩展文献综述，将覆盖率从{current_coverage:.1%}提升到至少80%',
                    'priority': 'medium',
                    'effort': 'high',
                    'timeline': '2-4周',
                    'expected_impact': 0.2,
                    'resources': ['文献数据库', '时间'],
                    'steps': [
                        '扩大文献搜索范围',
                        '使用多个数据库',
                        '系统性文献筛选',
                        '更新文献综述'
                    ]
                },
                'innovation_highlight': {
                    'template': '明确阐述{innovation_aspects}等创新点，突出研究的独特贡献',
                    'priority': 'medium',
                    'effort': 'low',
                    'timeline': '3-7天',
                    'expected_impact': 0.15,
                    'resources': ['写作时间'],
                    'steps': [
                        '识别研究创新点',
                        '与现有工作对比',
                        '撰写创新性说明',
                        '在各部分强调创新'
                    ]
                }
            },
            'impact': {
                'theoretical_contribution': {
                    'template': '深化理论贡献，阐述{theory_aspects}等理论价值',
                    'priority': 'medium',
                    'effort': 'medium',
                    'timeline': '1-3周',
                    'expected_impact': 0.2,
                    'resources': ['理论研究时间'],
                    'steps': [
                        '分析理论意义',
                        '与现有理论对比',
                        '阐述理论贡献',
                        '讨论理论影响'
                    ]
                },
                'practical_application': {
                    'template': '探讨{application_areas}等实践应用场景，提高研究的实用价值',
                    'priority': 'medium',
                    'effort': 'medium',
                    'timeline': '1-2周',
                    'expected_impact': 0.18,
                    'resources': ['应用调研时间'],
                    'steps': [
                        '识别应用领域',
                        '分析应用可行性',
                        '设计应用方案',
                        '评估应用效果'
                    ]
                }
            },
            'presentation': {
                'writing_clarity': {
                    'template': '改进语言表达，使用{clarity_techniques}等技巧提高写作清晰度',
                    'priority': 'medium',
                    'effort': 'medium',
                    'timeline': '1-2周',
                    'expected_impact': 0.15,
                    'resources': ['写作时间', '语言润色'],
                    'steps': [
                        '识别表达不清的部分',
                        '简化复杂句式',
                        '统一术语使用',
                        '请他人审阅'
                    ]
                },
                'structure_optimization': {
                    'template': '重新组织文章结构，采用{structure_patterns}等逻辑框架',
                    'priority': 'medium',
                    'effort': 'medium',
                    'timeline': '1-2周',
                    'expected_impact': 0.18,
                    'resources': ['重构时间'],
                    'steps': [
                        '分析现有结构',
                        '设计新的逻辑框架',
                        '重新组织内容',
                        '检查逻辑连贯性'
                    ]
                }
            },
            'ethics': {
                'ethics_approval': {
                    'template': '向{ethics_committees}等机构申请伦理审批，确保研究符合伦理标准',
                    'priority': 'critical',
                    'effort': 'high',
                    'timeline': '4-8周',
                    'expected_impact': 0.4,
                    'resources': ['申请费用', '文档准备'],
                    'steps': [
                        '准备伦理审批材料',
                        '提交审批申请',
                        '配合审查过程',
                        '获得审批证书'
                    ]
                },
                'bias_analysis': {
                    'template': '进行{bias_types}等偏见分析，并采取相应的缓解措施',
                    'priority': 'high',
                    'effort': 'medium',
                    'timeline': '1-2周',
                    'expected_impact': 0.25,
                    'resources': ['偏见分析工具'],
                    'steps': [
                        '识别潜在偏见类型',
                        '分析偏见来源',
                        '设计缓解策略',
                        '验证缓解效果'
                    ]
                }
            }
        }
        
        # 建议效果预测模型参数
        self.impact_factors = {
            'issue_severity': {
                'critical': 0.4,
                'high': 0.3,
                'medium': 0.2,
                'low': 0.1
            },
            'implementation_effort': {
                'low': 0.9,
                'medium': 0.7,
                'high': 0.5
            },
            'resource_availability': {
                'high': 0.9,
                'medium': 0.7,
                'low': 0.4
            }
        }
    
    async def generate_improvement_suggestions(self, issues: List[QualityIssue], 
                                             context: Optional[Dict[str, Any]] = None) -> List[Improvement]:
        """生成改进建议"""
        try:
            suggestions = []
            
            # 按问题类型分组
            issues_by_type = {}
            for issue in issues:
                issue_type = issue.issue_type
                if issue_type not in issues_by_type:
                    issues_by_type[issue_type] = []
                issues_by_type[issue_type].append(issue)
            
            # 为每个问题类型生成建议
            for issue_type, type_issues in issues_by_type.items():
                type_suggestions = await self._generate_suggestions_for_type(
                    issue_type, type_issues, context
                )
                suggestions.extend(type_suggestions)
            
            # 生成综合性建议
            comprehensive_suggestions = await self._generate_comprehensive_suggestions(
                issues, context
            )
            suggestions.extend(comprehensive_suggestions)
            
            # 排序和优化建议
            optimized_suggestions = await self._optimize_suggestions(suggestions, context)
            
            return optimized_suggestions
            
        except Exception as e:
            print(f"生成改进建议失败: {e}")
            return []
    
    async def _generate_suggestions_for_type(self, issue_type: str, issues: List[QualityIssue], 
                                           context: Optional[Dict[str, Any]]) -> List[Improvement]:
        """为特定类型的问题生成建议"""
        suggestions = []
        
        if issue_type not in self.suggestion_templates:
            return suggestions
        
        templates = self.suggestion_templates[issue_type]
        
        for issue in issues:
            # 根据问题描述匹配合适的模板
            matched_template = await self._match_template(issue, templates)
            
            if matched_template:
                suggestion = await self._create_suggestion_from_template(
                    issue, matched_template, context
                )
                if suggestion:
                    suggestions.append(suggestion)
        
        return suggestions
    
    async def _match_template(self, issue: QualityIssue, 
                            templates: Dict[str, Dict[str, Any]]) -> Optional[Dict[str, Any]]:
        """匹配合适的建议模板"""
        issue_desc = issue.description.lower()
        
        # 基于关键词匹配
        keyword_matches = {
            'sample_size': ['样本量', '样本', 'sample'],
            'randomization': ['随机', 'random'],
            'control_variables': ['控制变量', 'control'],
            'completeness': ['完整性', '缺失', 'complete', 'missing'],
            'reliability': ['可靠', '来源', 'reliable', 'source'],
            'method_selection': ['分析方法', '方法', 'method', 'analysis'],
            'statistical_testing': ['统计', '检验', 'statistical', 'test'],
            'code_sharing': ['代码', 'code'],
            'data_sharing': ['数据', 'data'],
            'documentation': ['文档', '说明', 'document'],
            'literature_review': ['文献', '综述', 'literature'],
            'innovation_highlight': ['创新', '新颖', 'innovation', 'novel'],
            'theoretical_contribution': ['理论', 'theoretical'],
            'practical_application': ['实践', '应用', 'practical', 'application'],
            'writing_clarity': ['清晰', '写作', 'clarity', 'writing'],
            'structure_optimization': ['结构', '组织', 'structure', 'organization'],
            'ethics_approval': ['伦理', '审批', 'ethics', 'approval'],
            'bias_analysis': ['偏见', 'bias']
        }
        
        for template_key, keywords in keyword_matches.items():
            if template_key in templates:
                if any(keyword in issue_desc for keyword in keywords):
                    return templates[template_key]
        
        # 如果没有匹配到，返回第一个模板作为默认
        return list(templates.values())[0] if templates else None
    
    async def _create_suggestion_from_template(self, issue: QualityIssue, 
                                             template: Dict[str, Any],
                                             context: Optional[Dict[str, Any]]) -> Optional[Improvement]:
        """基于模板创建改进建议"""
        try:
            # 生成建议描述
            description = await self._customize_template_description(
                template['template'], issue, context
            )
            
            # 预测改进效果
            expected_impact = await self._predict_improvement_impact(
                issue, template, context
            )
            
            # 估算实施时间
            timeline = await self._estimate_implementation_timeline(
                template, context
            )
            
            suggestion = Improvement(
                improvement_type=issue.issue_type,
                priority=template.get('priority', 'medium'),
                description=description,
                expected_impact=f"预期提升质量评分{expected_impact:.1%}",
                implementation_effort=template.get('effort', 'medium'),
                timeline_estimate=timeline
            )
            
            return suggestion
            
        except Exception as e:
            print(f"创建建议失败: {e}")
            return None
    
    async def _customize_template_description(self, template: str, issue: QualityIssue, 
                                            context: Optional[Dict[str, Any]]) -> str:
        """定制化模板描述"""
        description = template
        
        # 根据问题类型和上下文替换占位符
        if '{target_size}' in description:
            current_size = self._extract_number_from_text(issue.description)
            target_size = max(30, current_size * 2) if current_size else 100
            description = description.replace('{target_size}', str(target_size))
        
        if '{current_size}' in description:
            current_size = self._extract_number_from_text(issue.description)
            description = description.replace('{current_size}', str(current_size or 'unknown'))
        
        if '{methods}' in description:
            methods = ['简单随机化', '分层随机化', '区组随机化']
            description = description.replace('{methods}', '、'.join(methods))
        
        if '{suggested_vars}' in description:
            vars_list = ['年龄', '性别', '教育水平', '经济状况']
            description = description.replace('{suggested_vars}', '、'.join(vars_list))
        
        if '{current_rate}' in description:
            rate = self._extract_percentage_from_text(issue.description)
            description = description.replace('{current_rate}', str(rate or 0.5))
        
        if '{suggested_sources}' in description:
            sources = ['政府统计局', '权威研究机构', '同行评议期刊']
            description = description.replace('{suggested_sources}', '、'.join(sources))
        
        if '{suggested_methods}' in description:
            methods = ['多元回归分析', '结构方程模型', '机器学习方法']
            description = description.replace('{suggested_methods}', '、'.join(methods))
        
        if '{test_types}' in description:
            tests = ['t检验', 'ANOVA', '卡方检验']
            description = description.replace('{test_types}', '、'.join(tests))
        
        if '{platforms}' in description:
            platforms = ['GitHub', 'GitLab', 'Zenodo']
            description = description.replace('{platforms}', '、'.join(platforms))
        
        if '{privacy_requirements}' in description:
            requirements = ['GDPR', '数据保护法', '伦理委员会要求']
            description = description.replace('{privacy_requirements}', '、'.join(requirements))
        
        if '{doc_types}' in description:
            doc_types = ['方法说明', '数据字典', '代码文档', '使用指南']
            description = description.replace('{doc_types}', '、'.join(doc_types))
        
        if '{current_coverage}' in description:
            coverage = self._extract_percentage_from_text(issue.description)
            description = description.replace('{current_coverage}', str(coverage or 0.5))
        
        if '{innovation_aspects}' in description:
            aspects = ['新算法', '新数据集', '新应用领域', '新理论框架']
            description = description.replace('{innovation_aspects}', '、'.join(aspects))
        
        if '{theory_aspects}' in description:
            aspects = ['理论扩展', '概念创新', '模型改进']
            description = description.replace('{theory_aspects}', '、'.join(aspects))
        
        if '{application_areas}' in description:
            areas = ['工业应用', '医疗健康', '教育培训', '社会服务']
            description = description.replace('{application_areas}', '、'.join(areas))
        
        if '{clarity_techniques}' in description:
            techniques = ['简化句式', '统一术语', '增加示例', '逻辑连接']
            description = description.replace('{clarity_techniques}', '、'.join(techniques))
        
        if '{structure_patterns}' in description:
            patterns = ['IMRAD结构', '问题-方法-结果-讨论', '递进式论证']
            description = description.replace('{structure_patterns}', '、'.join(patterns))
        
        if '{ethics_committees}' in description:
            committees = ['机构伦理委员会', '学科伦理审查委员会']
            description = description.replace('{ethics_committees}', '、'.join(committees))
        
        if '{bias_types}' in description:
            bias_types = ['选择偏见', '确认偏见', '测量偏见', '报告偏见']
            description = description.replace('{bias_types}', '、'.join(bias_types))
        
        return description
    
    def _extract_number_from_text(self, text: str) -> Optional[int]:
        """从文本中提取数字"""
        import re
        numbers = re.findall(r'\d+', text)
        return int(numbers[0]) if numbers else None
    
    def _extract_percentage_from_text(self, text: str) -> Optional[float]:
        """从文本中提取百分比"""
        import re
        # 查找百分比格式
        percentages = re.findall(r'(\d+(?:\.\d+)?)%', text)
        if percentages:
            return float(percentages[0]) / 100
        
        # 查找小数格式
        decimals = re.findall(r'(\d\.\d+)', text)
        if decimals:
            return float(decimals[0])
        
        return None
    
    async def _predict_improvement_impact(self, issue: QualityIssue, 
                                        template: Dict[str, Any],
                                        context: Optional[Dict[str, Any]]) -> float:
        """预测改进效果"""
        base_impact = template.get('expected_impact', 0.2)
        
        # 根据问题严重程度调整
        severity_factor = self.impact_factors['issue_severity'].get(issue.severity, 0.2)
        
        # 根据实施难度调整
        effort_factor = self.impact_factors['implementation_effort'].get(
            template.get('effort', 'medium'), 0.7
        )
        
        # 根据资源可用性调整（如果有上下文信息）
        resource_factor = 0.7  # 默认值
        if context and 'resource_availability' in context:
            resource_factor = self.impact_factors['resource_availability'].get(
                context['resource_availability'], 0.7
            )
        
        # 计算综合影响
        predicted_impact = base_impact * severity_factor * effort_factor * resource_factor
        
        return min(1.0, predicted_impact)  # 限制在100%以内
    
    async def _estimate_implementation_timeline(self, template: Dict[str, Any], 
                                              context: Optional[Dict[str, Any]]) -> str:
        """估算实施时间"""
        base_timeline = template.get('timeline', '1-2周')
        
        # 根据上下文调整时间估算
        if context:
            if context.get('urgency') == 'high':
                # 紧急情况下缩短时间
                return self._adjust_timeline(base_timeline, 0.7)
            elif context.get('resource_availability') == 'low':
                # 资源不足时延长时间
                return self._adjust_timeline(base_timeline, 1.5)
        
        return base_timeline
    
    def _adjust_timeline(self, timeline: str, factor: float) -> str:
        """调整时间线"""
        import re
        
        # 提取时间范围
        match = re.search(r'(\d+)-(\d+)([周天月])', timeline)
        if match:
            start, end, unit = match.groups()
            new_start = max(1, int(int(start) * factor))
            new_end = max(new_start, int(int(end) * factor))
            return f"{new_start}-{new_end}{unit}"
        
        return timeline
    
    async def _generate_comprehensive_suggestions(self, issues: List[QualityIssue], 
                                                context: Optional[Dict[str, Any]]) -> List[Improvement]:
        """生成综合性改进建议"""
        suggestions = []
        
        # 分析问题模式
        issue_patterns = await self._analyze_issue_patterns(issues)
        
        # 生成系统性改进建议
        if issue_patterns['methodology_issues'] >= 3:
            suggestions.append(Improvement(
                improvement_type='comprehensive',
                priority='high',
                description='系统性改进研究方法论，建议寻求方法学专家指导',
                expected_impact='预期全面提升研究质量30-50%',
                implementation_effort='high',
                timeline_estimate='4-8周'
            ))
        
        if issue_patterns['reproducibility_issues'] >= 2:
            suggestions.append(Improvement(
                improvement_type='comprehensive',
                priority='high',
                description='建立完整的可重现性框架，包括代码、数据和文档标准化',
                expected_impact='预期显著提升研究可信度',
                implementation_effort='medium',
                timeline_estimate='2-4周'
            ))
        
        if issue_patterns['critical_issues'] > 0:
            suggestions.append(Improvement(
                improvement_type='urgent',
                priority='critical',
                description='优先解决严重问题，建议暂停研究进展直到关键问题得到解决',
                expected_impact='避免研究失败风险',
                implementation_effort='high',
                timeline_estimate='立即执行'
            ))
        
        # 基于问题分布生成建议
        if len(set(issue.issue_type for issue in issues)) >= 5:
            suggestions.append(Improvement(
                improvement_type='comprehensive',
                priority='medium',
                description='问题涉及多个维度，建议制定全面的质量改进计划',
                expected_impact='预期整体提升研究质量',
                implementation_effort='high',
                timeline_estimate='6-12周'
            ))
        
        return suggestions
    
    async def _analyze_issue_patterns(self, issues: List[QualityIssue]) -> Dict[str, int]:
        """分析问题模式"""
        patterns = {
            'methodology_issues': 0,
            'data_quality_issues': 0,
            'reproducibility_issues': 0,
            'ethics_issues': 0,
            'critical_issues': 0,
            'high_priority_issues': 0
        }
        
        for issue in issues:
            if issue.issue_type == 'methodology':
                patterns['methodology_issues'] += 1
            elif issue.issue_type == 'data_quality':
                patterns['data_quality_issues'] += 1
            elif issue.issue_type == 'reproducibility':
                patterns['reproducibility_issues'] += 1
            elif issue.issue_type == 'ethics':
                patterns['ethics_issues'] += 1
            
            if issue.severity == 'critical':
                patterns['critical_issues'] += 1
            elif issue.severity == 'high':
                patterns['high_priority_issues'] += 1
        
        return patterns
    
    async def _optimize_suggestions(self, suggestions: List[Improvement], 
                                  context: Optional[Dict[str, Any]]) -> List[Improvement]:
        """优化和排序建议"""
        # 去重
        unique_suggestions = []
        seen_descriptions = set()
        
        for suggestion in suggestions:
            if suggestion.description not in seen_descriptions:
                unique_suggestions.append(suggestion)
                seen_descriptions.add(suggestion.description)
        
        # 排序
        sorted_suggestions = await self._sort_suggestions_by_priority(
            unique_suggestions, context
        )
        
        # 限制数量
        max_suggestions = context.get('max_suggestions', 15) if context else 15
        
        return sorted_suggestions[:max_suggestions]
    
    async def _sort_suggestions_by_priority(self, suggestions: List[Improvement], 
                                          context: Optional[Dict[str, Any]]) -> List[Improvement]:
        """按优先级排序建议"""
        priority_order = {'critical': 0, 'high': 1, 'medium': 2, 'low': 3}
        effort_order = {'low': 0, 'medium': 1, 'high': 2}
        
        def priority_score(suggestion: Improvement) -> Tuple[int, int]:
            priority_val = priority_order.get(suggestion.priority, 3)
            effort_val = effort_order.get(suggestion.implementation_effort, 1)
            
            # 优先级高且实施难度低的建议排在前面
            return (priority_val, effort_val)
        
        return sorted(suggestions, key=priority_score)
    
    async def create_improvement_plan(self, suggestions: List[Improvement], 
                                    context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """创建改进计划"""
        plan = {
            'total_suggestions': len(suggestions),
            'phases': [],
            'timeline': '',
            'resource_requirements': [],
            'expected_outcomes': [],
            'risk_assessment': []
        }
        
        # 按优先级分阶段
        critical_suggestions = [s for s in suggestions if s.priority == 'critical']
        high_suggestions = [s for s in suggestions if s.priority == 'high']
        medium_suggestions = [s for s in suggestions if s.priority == 'medium']
        low_suggestions = [s for s in suggestions if s.priority == 'low']
        
        phase_num = 1
        
        if critical_suggestions:
            plan['phases'].append({
                'phase': phase_num,
                'name': '紧急问题处理',
                'suggestions': critical_suggestions,
                'timeline': '立即-1周',
                'priority': 'critical'
            })
            phase_num += 1
        
        if high_suggestions:
            plan['phases'].append({
                'phase': phase_num,
                'name': '高优先级改进',
                'suggestions': high_suggestions,
                'timeline': '1-4周',
                'priority': 'high'
            })
            phase_num += 1
        
        if medium_suggestions:
            plan['phases'].append({
                'phase': phase_num,
                'name': '中等优先级改进',
                'suggestions': medium_suggestions,
                'timeline': '4-8周',
                'priority': 'medium'
            })
            phase_num += 1
        
        if low_suggestions:
            plan['phases'].append({
                'phase': phase_num,
                'name': '长期优化',
                'suggestions': low_suggestions,
                'timeline': '8-12周',
                'priority': 'low'
            })
        
        # 估算总时间线
        if plan['phases']:
            plan['timeline'] = f"总计 {len(plan['phases'])} 个阶段，预计 {self._estimate_total_timeline(plan['phases'])} 完成"
        
        # 汇总资源需求
        all_resources = set()
        for suggestion in suggestions:
            # 从模板中提取资源需求（简化实现）
            if suggestion.implementation_effort == 'high':
                all_resources.update(['专业人员', '充足时间', '资金支持'])
            elif suggestion.implementation_effort == 'medium':
                all_resources.update(['一般人员', '适中时间'])
            else:
                all_resources.update(['基本时间'])
        
        plan['resource_requirements'] = list(all_resources)
        
        # 预期结果
        plan['expected_outcomes'] = [
            '研究质量显著提升',
            '问题数量大幅减少',
            '研究可信度增强',
            '发表成功率提高'
        ]
        
        # 风险评估
        plan['risk_assessment'] = [
            '时间延期风险：中等',
            '资源不足风险：低',
            '实施困难风险：中等',
            '效果不达预期风险：低'
        ]
        
        return plan
    
    def _estimate_total_timeline(self, phases: List[Dict[str, Any]]) -> str:
        """估算总时间线"""
        if not phases:
            return "未知"
        
        # 简化实现：假设阶段可以部分重叠
        total_weeks = 0
        for phase in phases:
            timeline = phase.get('timeline', '1-2周')
            # 提取最大周数
            import re
            match = re.search(r'(\d+)周', timeline)
            if match:
                weeks = int(match.group(1))
                total_weeks = max(total_weeks, weeks)
            else:
                total_weeks += 2  # 默认2周
        
        return f"{total_weeks}周"
    
    async def track_improvement_progress(self, plan: Dict[str, Any], 
                                       completed_suggestions: List[str]) -> Dict[str, Any]:
        """跟踪改进进度"""
        progress = {
            'overall_progress': 0.0,
            'phase_progress': [],
            'completed_count': len(completed_suggestions),
            'remaining_count': 0,
            'next_actions': []
        }
        
        total_suggestions = plan['total_suggestions']
        progress['overall_progress'] = len(completed_suggestions) / total_suggestions if total_suggestions > 0 else 0
        
        # 计算各阶段进度
        for phase in plan['phases']:
            phase_suggestions = phase['suggestions']
            completed_in_phase = sum(1 for s in phase_suggestions 
                                   if s.description in completed_suggestions)
            phase_progress = completed_in_phase / len(phase_suggestions) if phase_suggestions else 0
            
            progress['phase_progress'].append({
                'phase': phase['phase'],
                'name': phase['name'],
                'progress': phase_progress,
                'completed': completed_in_phase,
                'total': len(phase_suggestions)
            })
        
        progress['remaining_count'] = total_suggestions - len(completed_suggestions)
        
        # 确定下一步行动
        for phase in plan['phases']:
            incomplete_suggestions = [s for s in phase['suggestions'] 
                                    if s.description not in completed_suggestions]
            if incomplete_suggestions:
                progress['next_actions'] = incomplete_suggestions[:3]  # 最多3个下一步行动
                break
        
        return progress